package org.youchan.aco.ui;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Image;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLEditorKit;

import org.youchan.aco.FetchProfileCommand;
import org.youchan.aco.ImageLoader;
import org.youchan.aco.MembersListManager;
import org.youchan.aco.model.Member;
import org.youchan.aco.model.MemberLevel;
import org.youchan.aco.model.MemberProfile;
import org.youchan.aco.model.Message;

@SuppressWarnings("serial")
public class DetailedMessagePanel extends JPanel {
	
	@SuppressWarnings("unused")
	private static final Logger LOGGER = Logger.getLogger(DetailedMessagePanel.class.getCanonicalName());
	private static final SimpleDateFormat DF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	
	private JLabel mIconLabel;
	private JEditorPane mTextPane;
	private JEditorPane mProfilePane;
	private JLabel mDateLabel;
	private JScrollPane mScrollPane;
	MyImageLoader imageLoader;
	
	public DetailedMessagePanel() {
		super();
		imageLoader = new MyImageLoader();
		init();
	}
	
	private void init() {
		this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		
		mIconLabel = new JLabel();
		this.add(mIconLabel);
		
		HyperlinkListener hyperlinkListener = new HyperlinkListener() {
			public void hyperlinkUpdate(HyperlinkEvent e) {
				try {
					if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
						Desktop.getDesktop().browse(e.getURL().toURI());
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				} catch (URISyntaxException e1) {
					e1.printStackTrace();
				}
			}
			
		};

		mTextPane = new JEditorPane();
		HTMLEditorKit editorKit = new HTMLEditorKit();
		mTextPane.setEditorKit(editorKit);
		mTextPane.setEditable(false);
		mTextPane.addHyperlinkListener(hyperlinkListener);
		
		mScrollPane = new JScrollPane(mTextPane);
		mScrollPane.setAutoscrolls(false);

		mProfilePane = new JEditorPane();
		mProfilePane.setEditorKit(editorKit);
		mProfilePane.setEditable(false);
		mProfilePane.addHyperlinkListener(hyperlinkListener);
		mProfilePane.setMaximumSize(new Dimension(400, 24));
		mProfilePane.setBorder(BorderFactory.createEmptyBorder());
		
		mDateLabel = new JLabel();
		mDateLabel.setBackground(Color.white);
		mDateLabel.setOpaque(true);
		
		Box vBox = Box.createVerticalBox();
		Box hBox = Box.createHorizontalBox();
		hBox.setBackground(Color.white);
		hBox.setOpaque(true);
		hBox.setMaximumSize(new Dimension(800, 16));
		hBox.add(mProfilePane);
		hBox.add(mDateLabel);
		hBox.setOpaque(true);
		vBox.add(hBox);
		vBox.add(mScrollPane);
		this.add(vBox);

		this.setBorder(BorderFactory.createEmptyBorder());
	}
	
	public void setMessage(Message message) {
		String text = message.getText();
		String id = "";
		Member member = null;
		MemberProfile profile = null;
		if (message.getMemberId().equals("")) {
			id = message.getTwitterId();
			member = MembersListManager.getInstance().getMembersList().getMemberByTwitterId(id);
		}
		
		if (member == null) {
			member = new Member();
			member.setTwitterId(id);
			member.setMemberLevel(MemberLevel.TWITTER);
		} else {
			profile = member.getProfile();
		}

		if (profile == null || profile.getImageURL() == null) {
			sendFetchProfileCommand(member);
		} else {
			try {
				profile.getImageURL().hashCode();
				imageLoader.loadImageByMember(member);
			} catch (NullPointerException e) {
				sendFetchProfileCommand(member);
			}
		}
		text = text.replaceAll("https?://[\\w\\./]+", "<a href=\"$0\">$0</a>");
		mTextPane.setText("<html><span style=\"font-size:90%;\">" + text + "</span></html>");
		mProfilePane.setText("<html><span style=\"font-size:90%;\"><a href=\"http://twitter.com/" + id + "\"><b>" + id + "</b></a></span></html>");
		mIconLabel.setIcon(null);
		mDateLabel.setText(" [" + DF.format(message.getTimestamp()) + "]");
	}

	void sendFetchProfileCommand(Member member) {
		FetchProfileCommand command = new FetchProfileCommand(member, imageLoader);
		MembersListManager.getInstance().sendCommand(command);
	}

	class MyImageLoader extends ImageLoader {
		public void imageLoaded(final Image image, Member member) {
			MemberProfile profile = member.getProfile();
			final String id = member.getTwitterId();
			final String name = profile.getName();
			SwingUtilities.invokeLater(
					new Runnable() {
						public void run() {
							mProfilePane.setText(
									"<html><span style=\"font-size:90%;\"><a href=\"http://twitter.com/" + id + "\"><b>" + id + "/" + name + "</b></a></span></html>");
							mIconLabel.setIcon(new ImageIcon(image));
						}
					}
			);
		}
	}
}